package client;

import static debug.Debug.DBUG;

import java.io.*;
import java.net.*;

public class ServerConnection {
	
	private String server;
	private int port;
	private String username;
	private Socket sock;
	private BufferedWriter out;
	private BufferedReader in;
	private AlfaListener listener;
	
	public ServerConnection() {
		server = "localhost";
		port = 4343;
		sock = new Socket();
		listener = new AlfaListener(this);
	}
	
	public void setServer(String server, int port) {
		this.server = server;
		this.port = port;
	}

	public void connect() {
		try {
			sock.connect(new InetSocketAddress(server, port));
			DBUG("connected");
		} catch (IOException e) {
			DBUG("COULD NOT CONNECT");
		}
		try {
			out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
		} catch (IOException e) {
			DBUG("COULD NOT GET IN/OUT STREAM");
		}
		listener.setInstream(in);
		new Thread(listener).start();
	}
	
	public void close() {
		try {
			sock.close();
			DBUG("connection closed");
		} catch (IOException e) {
			DBUG("UNABLE TO CLOSE");
		}
	}
	
	public AlfaListener getListener() {
		return listener;
	}
	
	public void send(String msg) {
		while (msg.endsWith("\n"))
			msg = msg.substring(0, msg.length()-1);
		
		try {
			out.write(msg+"\n");
			out.flush();
			DBUG("> "+ msg);
		} catch (IOException e) {
			DBUG("COULD NOT WRITE");
		}
	}
	
	public void login(String user, String pass) {
		username = user;
		DBUG("connecting to "+ server +":"+ port);
		connect();
		send("login "+ user +" "+ pass);
	}

	public void sendMoving(int x, int y) {
		send("moving "+ x +" "+ y);
	}
	public void sendMovestop() {
		send ("movestop");
	}

	public void sendMove(int x, int y) {
		send("move "+ x +" "+ y);
	}
}
